import type { Request, Response, NextFunction } from 'express'

export class APIError extends Error {
  statusCode: number
  retryable: boolean
  
  constructor(message: string, statusCode = 500, retryable = true) {
    super(message)
    this.name = 'APIError'
    this.statusCode = statusCode
    this.retryable = retryable
  }
}

export const errorMiddleware = (
  err: Error,
  _req: Request,
  res: Response,
  _next: NextFunction
) => {
  console.error('Error:', err)
  
  if (err instanceof APIError) {
    res.status(err.statusCode).json({
      success: false,
      error: err.message,
      retryable: err.retryable,
    })
    return
  }
  
  res.status(500).json({
    success: false,
    error: 'Internal server error',
    retryable: true,
  })
}
